// 防抖
const _debounce = (fn, delay = 200) => {
  let timer;
  return function() {
    let th = this;
    let args = arguments;
    if (timer) {
      clearTimeout(timer);
    }
    timer = setTimeout(function() {
      timer = null;
      fn.apply(th, args);
    }, delay);
  };
};

/**
 * @param {string} url
 * @returns {Object}
 */
const param2Obj = url => {
  const search = decodeURIComponent(url.split("?")[1]).replace(/\+/g, " ");
  if (!search) {
    return {};
  }
  const obj = {};
  const searchArr = search.split("&");
  searchArr.forEach(v => {
    const index = v.indexOf("=");
    if (index !== -1) {
      const name = v.substring(0, index);
      const val = v.substring(index + 1, v.length);
      obj[name] = val;
    }
  });
  return obj;
};

const componentDataToArray = data => {
  var arr = [];

  for (let i in data) {
    arr[i] = data[i];
    arr[i].id = i;
  }

  return Object.values(arr);
};

/**
 * 获取分类标题
 * @param cate 分类原始数据
 * @returns {string}
 */
const getCateTitle = cate => {
  if (cate.length === 0) {
    return "暂无分类";
  }
  let arr = [];
  cate.forEach(item => {
    arr.push(`<span>${item.title}</span>`);
  });
  return arr.join("");
};

/**
 * 分类转换成树形结构
 *
 * @param {*} source
 * @param {*} id
 * @param {*} parentId
 * @param {*} children
 * @returns
 */
const treeData = (source, id, parentId, children) => {
  let cloneData = JSON.parse(JSON.stringify(source));
  return cloneData.filter(father => {
    let branchArr = cloneData.filter(child => father[id] == child[parentId]);
    branchArr.length > 0 ? (father[children] = branchArr) : "";
    return father[parentId] == 0 || father[parentId] == null; // 如果第一层不是parentId=0，请自行修改
  });
};

export { _debounce, param2Obj, componentDataToArray, getCateTitle, treeData };
